package com.hb.trade.server.project.file.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.enums.DeployStatusEnum;
import com.hb.core.pojo.project.file.dto.BidFileInfoDTO;
import com.hb.core.pojo.project.file.entity.BidFileInfo;
import com.hb.core.pojo.project.file.mapper.BidFileInfoMapper;
import com.hb.core.pojo.project.notice.mapper.NoticeMapper;
import com.hb.core.pojo.project.section.dto.BidSectionDTO;
import com.hb.core.pojo.project.section.entity.BidSection;
import com.hb.trade.server.project.file.manager.BidFileInfoManager;
import com.hb.trade.server.project.file.service.BidFileInfoService;
import com.hb.trade.server.project.file.service.ReviewItemFirstService;
import com.hb.trade.server.project.file.service.ReviewItemSecondService;
import com.hb.trade.server.project.file.service.ReviewItemThirdService;
import com.hb.trade.server.project.opening.service.BidOpeningScheduleService;
import com.hb.trade.server.project.proj.service.BidFileInfoInsService;
import com.hb.trade.server.project.section.service.raw.BidSectionService;
import org.fzzn.core.model.enums.LogicEnum;
import org.fzzn.core.util.Enums;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 招标文件 服务实现类
 * </p>
 *
 * @author zhongdl
 * @since 2021-09-16
 */
@Service
public class BidFileInfoServiceImpl extends ServiceImpl<BidFileInfoMapper, BidFileInfo> implements BidFileInfoService {

    protected final BidSectionService bidSectionService;
    protected final ReviewItemFirstService reviewItemFirstService;
    protected final ReviewItemSecondService reviewItemSecondService;
    protected final ReviewItemThirdService reviewItemThirdService;
    protected final BidFileInfoInsService bidFileInfoInsService;
    protected final BidOpeningScheduleService bidOpeningScheduleService;
    protected final NoticeMapper noticeMapper;

    public BidFileInfoServiceImpl(BidSectionService bidSectionService,
                                  ReviewItemFirstService reviewItemFirstService,
                                  ReviewItemSecondService reviewItemSecondService,
                                  ReviewItemThirdService reviewItemThirdService,
                                  BidFileInfoInsService bidFileInfoInsService,
                                  BidOpeningScheduleService bidOpeningScheduleService,
                                  NoticeMapper noticeMapper) {
        this.bidSectionService = bidSectionService;
        this.reviewItemFirstService = reviewItemFirstService;
        this.reviewItemSecondService = reviewItemSecondService;
        this.reviewItemThirdService = reviewItemThirdService;
        this.bidFileInfoInsService = bidFileInfoInsService;
        this.bidOpeningScheduleService = bidOpeningScheduleService;
        this.noticeMapper = noticeMapper;
    }

    @Override
    public List<JSONObject> findBidFileInfoListByProjectId(Long projectId) {
        return baseMapper.findBidFileInfoListByProjectId(projectId);
    }

    @Override
    public boolean findBidFileInfoTypeBySectionId(Long sectionId) {
        Integer releaseFlag = baseMapper.findBidFileInfoTypeBySectionId(sectionId);
        return Enums.equals(LogicEnum.NO, releaseFlag);
    }

    /**
     * 查询指定项目ID的招标文件列表
     *
     * @param bidFileInfoDTO
     * @return
     * @update zhaojk
     */
    @Override
    public Page<BidFileInfo> pageFilesByProjectId(BidFileInfoDTO bidFileInfoDTO) {
        Page<BidFileInfo> pages = bidFileInfoDTO.pages();
        Long projectId = bidFileInfoDTO.getProjectId();
        QueryWrapper<BidFileInfo> wrapper = BidFileInfo.wrapper();
        wrapper.eq("project_id", projectId);
        return page(pages, wrapper);
    }
    /**
     *
     * @Description:查询指定项目ID的招标文件列表
     * @Author: zhongdl
     * @Date:2022/1/17 9:11
     * @param bidFileInfoDTO:
     * @return: {@link List< BidFileInfo> }
     **/
    @Override
    public List<BidFileInfo> listFilesByProjectId(BidFileInfoDTO bidFileInfoDTO) {
        QueryWrapper<BidFileInfo> wrapper = BidFileInfo.wrapper();
        wrapper.eq("project_id", bidFileInfoDTO.getProjectId());
        return list(wrapper);
    }

    /**
     * 保存招标文件
     *
     * @param bidFileInfo
     * @return
     * @update zhaojk
     */
    @Transactional
    @Override
    public boolean saveBidFileInfo(BidFileInfoDTO bidFileInfo) {
        // 标段属性设置
        BidSectionDTO options = bidFileInfo.getSectionOptions();
        if (options != null) {
            JSONConfig config = JSONConfig.create();
            config.setDateFormat(DatePattern.NORM_DATETIME_PATTERN);
            JSONObject sectionJSON = JSONUtil.parseObj(options);
            bidFileInfo.setSectionInfo(sectionJSON.toString());
        }

        boolean saveResult;

        // 保存招标文件主体信息
        Long primaryKey = bidFileInfo.getId();
        BidFileInfo org;
        if (primaryKey != null) {
            org = getById(primaryKey);
            if (org == null) {
                log.warn("招标文件数据不存在");
                return false;
            }

            // 验证发布状态
            Integer releaseFlag = org.getReleaseFlag();
            if (Enums.equals(DeployStatusEnum.DEPLOYED, releaseFlag)) {
                log.warn("招标文件已经发布, 保存失败");
                return false;
            }

            // 更新招标文件信息
            BeanUtil.copyProperties(bidFileInfo, org, CopyOptions.create().ignoreNullValue());
            org.buildBaseData(2);
            saveResult = updateById(org);

            // 如果招标文件是修改操作, 需要更新一下已经关联的标段信息
            if (saveResult) {
                refreshSectionWithBidFile(primaryKey);
            }
        } else {
            bidFileInfo.buildBaseData(1);
            saveResult = save(bidFileInfo);
        }
        return saveResult;
    }

    @Transactional
    @Override
    public void refreshSectionWithBidFile(Long fileId) {
        if (fileId == null) {
            return;
        }

        // 招标文件主体信息
        BidFileInfo fileInfo = getById(fileId);
        if (fileInfo == null) {
            return;
        }

        // 查询该招标文件关联的标段
        QueryWrapper<BidSection> wrapper = BidSection.wrapper();
        wrapper.eq("file_id", fileId);
        List<BidSection> bidSections = bidSectionService.list(wrapper);

        // 未关联任何标段
        if (CollUtil.isEmpty(bidSections)) {
            return;
        }

        for (BidSection bidSection : bidSections) {
            BidFileInfoManager fileInfoManager = fileInfo.to(BidFileInfoManager.class);
            BidSectionDTO sectionOptions = fileInfoManager.getSectionOptions();
            sectionOptions.to(bidSection);
            bidSectionService.updateById(bidSection);
        }
    }

    /**
     * 查询招标文件详情
     * 获取所有与该招标文件的标段将信息返回
     *
     * @param fileId
     * @return
     * @update zhaojk
     */
    @Override
    public BidFileInfoDTO getBidFileDetail(Long fileId) {
        // 查询招标文件详情
        BidFileInfo info = getById(fileId);
        if (info == null) {
            return null;
        }
        BidFileInfoManager fileManager = info.to(BidFileInfoManager.class);

        fileManager.setSectionOptions();

        return fileManager;
    }


    /**
     * 变更流程
     * @author tian
     * @date 2022-4-13 13:13
     * @param bidFileInfoDTO
     * @return java.lang.String
     */
    @Override
    @Transactional
    public String changeProcess(BidFileInfoDTO bidFileInfoDTO) {
        // 先查询是否存在已发布的招标文件
        QueryWrapper<BidFileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BidFileInfo::getProjectId, bidFileInfoDTO.getProjectId())
                .eq(BidFileInfo::getReleaseFlag, "1");
        List<BidFileInfo> bidFileInfoByReleaseFlag = baseMapper.selectList(queryWrapper);
        if(CollUtil.isNotEmpty(bidFileInfoByReleaseFlag)){
            return "变更失败，当前招标项目已存在发布的招标文件";
        }

        queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BidFileInfo::getProjectId, bidFileInfoDTO.getProjectId());
        List<BidFileInfo> bidFileInfos = baseMapper.selectList(queryWrapper);

        if(CollUtil.isNotEmpty(bidFileInfos)){
            // 根据前端传输的流程类型判断是否一致，与当前流程类型一致无法变更
            BidFileInfo fileInfo = bidFileInfos.get(0);
            if(null != fileInfo.getSimpleOrStandard() && fileInfo.getSimpleOrStandard().equals(bidFileInfoDTO.getSimpleOrStandard())){
                return "变更失败，当前流程与待变更的流程类型一致";
            }

            for (BidFileInfo bidFileInfo:bidFileInfos) {
                Map deleteMap = new HashMap();
                deleteMap.put("file_id", bidFileInfo.getId());
                // 删除评审项
                reviewItemFirstService.removeByMap(deleteMap);
                reviewItemSecondService.removeByMap(deleteMap);
                reviewItemThirdService.removeByMap(deleteMap);
                // 删除招标文件附件
                bidFileInfoInsService.removeByMap(deleteMap);
                // 删除开标一览表
                bidOpeningScheduleService.removeByMap(deleteMap);
                // 删除招标文件
                baseMapper.deleteById(bidFileInfo);
            }
        }
        return  "操作成功";
    }


    /**
     * 查询招标项目是否已创建了流程
     * @author tian
     * @date 2022-4-19 13:35
     * @param bidFileInfoDTO
     * @return org.fzzn.core.model.msg.Message<java.lang.Integer>
     */
    @Override
    public Integer selectSimpleOrStandard(BidFileInfoDTO bidFileInfoDTO) {
        QueryWrapper<BidFileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BidFileInfo::getProjectId, bidFileInfoDTO.getProjectId());
        List<BidFileInfo> bidFileInfos = baseMapper.selectList(queryWrapper);
        if(CollUtil.isNotEmpty(bidFileInfos)){
            return bidFileInfos.get(0).getSimpleOrStandard();
        }
        return null;
    }

    /**
     * 查询招标项目是否存在已发布的招标文件
     * @author tian
     * @date 2022-4-19 14:49
     * @param bidFileInfoDTO
     * @return java.lang.Integer
     */
    @Override
    public Integer selectReleaseFlag(BidFileInfoDTO bidFileInfoDTO) {
        // 先查询是否存在已发布的招标文件
        QueryWrapper<BidFileInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BidFileInfo::getProjectId, bidFileInfoDTO.getProjectId())
                .eq(BidFileInfo::getReleaseFlag, "1");
        List<BidFileInfo> bidFileInfoByReleaseFlag = baseMapper.selectList(queryWrapper);
        if(CollUtil.isNotEmpty(bidFileInfoByReleaseFlag)){
            return bidFileInfoByReleaseFlag.size();
        }
        return 0;
    }

    /**
     * @Description: 根据公告ID查询已发布的招标文件
     *
     * @author yuezheng
     * @param noticeId
     * @return org.fzzn.core.model.msg.Message<java.util.List<com.hb.core.pojo.project.file.dto.BidFileInfoDTO>>
     * @date 2022/6/23 14:18
     */
    @Override
    public List<BidFileInfoDTO> selectReleaseBidFileByNoticeId(Long noticeId) {
        return this.noticeMapper.selectReleaseBidFileByNoticeId(noticeId);
    }
}
